package core.proto;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

import org.apache.commons.lang.StringUtils;

import prefuse.util.ui.UILib;
import app.constants.CollabVizConstants;
import app.exceptions.CollabVizException;
import app.service.xml.XMLService;
import app.util.AppUtil;
import app.util.PropertyLoaderUtil;
import app.xml.model.AnnotationTag;
import app.xml.model.DateTag;
import app.xml.model.FileHistoryTag;
import app.xml.model.FileTag;
import app.xml.model.NoteTag;
import core.proto.vis.VizDemoRadial;
import core.util.logging.SimpleLogger;
import core.util.logging.constants.Location;

public class AllComponentsLegacy extends JPanel implements MouseListener {

    private static final SimpleLogger LOGGER = SimpleLogger.getLogger();

    private static final long serialVersionUID = 1L;

    private static PaintDoc document;

    private static PaintDoc document2;

    private static ClosableTabbedPane multipleDocs = new ClosableTabbedPane();

    public static ArrayList<String> openTabs = new ArrayList<String>();

    // private static GroupLayout layout;
    //
    // private static GroupLayout.SequentialGroup hGroup;
    //
    // private static GroupLayout.SequentialGroup vGroup;

    private static JSlider slider;

    static final int width = 1280;

    static final int height = 960;

    private static PropertyLoaderUtil propLoader;

    public static PropertyLoaderUtil getPropLoader() {
        return propLoader;
    }

    private static XMLService xmlService;

    static String imagePath;

    private static String notesImagePath;

    private static String htmlFolderPath = null;

    public static String getHtmlRootFolderPath() {
        return htmlFolderPath;
    }

    static JPanel directory;

    static JPanel directory2;

    // private static JEditorPane document = new JEditorPane();

    private static JPanel viz = VizDemoRadial.demo(VizDemoRadial.DATA_FILE,
            "name", 360, 440);

    private static JTabbedPane notes = new JTabbedPane();

    private static JSplitPane sp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

    public static JSplitPane sp2 = new JSplitPane();

    private static JSplitPane sp3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

    private static JSplitPane sp4 = new JSplitPane();

    private static String htmlFilePath;

    private static FileTag fileTag;

    public static FileTag getFileTag() {
        return fileTag;
    }

    private static JEditorPane historyText;

    private static JScrollPane historyScroll;

    private static JScrollPane notesScroll;

    private static List<String> xmlFileList;

    private static FileTag historyFileTag;

    private static FileHistoryTag hisFileTag;

    private static FileHistoryTag tempHisTag;

    private static String historyFilePath;

    private static String xmlFileName;

    private static JPanel docMiscArea = new JPanel();

    private static JSplitPane sp5 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

    private static JSplitPane sp6 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

    private static JPanel notesPanel = new JPanel();

    private static JTextArea notesArea = new JTextArea();

    private static JButton notesSaveButton = new JButton();

    private static String saveOption;

    private static HistoryRenderer historyRenderer;

    static MotionCanvas canvas;

    private static ToolbarLegacy toolbar = new ToolbarLegacy(1);

    private static ToolbarLegacy toolbar2 = new ToolbarLegacy(2);

    private static SearchBar searchBar;

    private static int windowType;

    static MouseListener tabDrag;

    public static final int ALL_VIEW = 0;
    public static final int NO_VIZ_VIEW = 1;
    public static final int NO_NOTES_VIEW = 2;
    public static final int NO_VIZNOTES_VIEW = 3;
    private static int selectedView;

    // static float x=0;
    // static float y=0;

    // public static void main(String[] args) throws IOException,
    // CollabVizException {
    // UILib.setPlatformLookAndFeel();
    // if (args.length != 1) {
    // System.out
    // .println("Please pass the absolute path to the config file.");
    // } else {
    // init(args[0]);
    // directory = new FileTree(new File(propLoader
    // .getProp(CollabVizConstants.HTML_FILES_FOLDER)));
    // new AllComponents();
    // }
    //
    // }

    public AllComponentsLegacy(String path, int window, int selectedView,
            boolean screenCap) throws IOException, CollabVizException {
        super();
        SimpleLogger.setScreenCap(screenCap);
        windowType = window;
        this.selectedView = selectedView;
        UILib.setPlatformLookAndFeel();
        init(path);
        htmlFolderPath = propLoader
                .getProp(CollabVizConstants.HTML_FILES_FOLDER);
        directory = new FileTree(new File(htmlFolderPath), 1);

        // imagePath = this.getClass()
        // .getResource( CollabVizConstants.COMMENTS_IMG ).toString();
        // notesImagePath = this.getClass()
        // .getResource( CollabVizConstants.NOTES_IMG ).toString();

        imagePath = this.getClass()
                .getResource(CollabVizConstants.COMMENTS_IMG).getPath();
        notesImagePath = this.getClass().getResource(
                CollabVizConstants.NOTES_IMG).getPath();

        document = new PaintDoc();
        document.addMouseListener(this);

        viz.addComponentListener(new ComponentListener() {
            @Override
            public void componentShown(ComponentEvent e_) {
            }

            @Override
            public void componentResized(ComponentEvent e) {
                System.out.println(e.getComponent().getClass().getName()
                        + " --- Resized width = " + viz.getWidth()
                        + " height = " + viz.getHeight());
                for (int i = 0; i < viz.getComponentCount(); i++) {
                    if (viz.getComponent(i) instanceof VizDemoRadial) {
                        VizDemoRadial visual = (VizDemoRadial) viz
                                .getComponent(i);
                        visual.resizeAndRun(viz.getWidth(), viz.getHeight());
                        sp2.updateUI();
                        break;
                    }
                }
                LOGGER.log(Location.VZ, "visualization frame resized");
            }

            @Override
            public void componentMoved(ComponentEvent e_) {
            }

            @Override
            public void componentHidden(ComponentEvent e_) {
            }
        });

        setSize(width, height);
        setProperties(directory, 220, 560);
        setProperties(viz, 360, 440);
        viz.setBackground(Color.white);
        setProperties(notes, 360, 260);

        notes = addHistoryComponent(notes);
        notes.setSize(360, 220);
        notes.setVisible(true);
        // notesScroll = new JScrollPane(notes);
        // notesScroll.setSize(360, 220);
        // notesScroll.setVisible(true);

        document.setSize(700, 560);
        toolbar.setSize(700, 100);
        JScrollPane scroll = new JScrollPane(document);
        scroll.setSize(700, 560);
        document.setDragEnabled(true);
        document.setEditable(false);

        // create Panel for drop targets to save
        createFileSavePanel();

        // notesArea = new JTextArea("", 4, 20);
        // notesArea.setFont(new Font("Arial", Font.PLAIN, 12));
        // notesArea.setVisible(false);
        // notesArea.setForeground(Color.BLACK);
        // notesArea.setVisible(true);
        // JScrollPane notesAreaScroll = new JScrollPane(notesArea);
        // notesAreaScroll = new JScrollPane(notesArea);
        // notesAreaScroll.setVisible(true);

        // ImageIcon saveImgIcon = new ImageIcon(this.getClass().getResource(
        // CollabVizConstants.SAVE_IMG));
        // ImageIcon notesImgIcon = new ImageIcon(this.getClass().getResource(
        // CollabVizConstants.NOTES_IMG));
        // JLabel picLabel = new JLabel(notesImgIcon);
        // picLabel.setVisible(true);
        // picLabel.setEnabled(true);
        // picLabel.setBounds(0, 0, 50, 50);

        // notesSaveButton.addActionListener(new NotesActionListener());
        // notesSaveButton.setIcon(saveImgIcon);
        // notesSaveButton.setSize(80, 80);

        // Radio button panel
        // JPanel radioPanel = new JPanel(new GridLayout(2, 0));

        // // trial creating the radio buttons
        // JRadioButtonMenuItem annoButton = new JRadioButtonMenuItem(
        // new ImageIcon(imagePath));
        // annoButton.setMnemonic(KeyEvent.VK_P);
        // annoButton.setActionCommand("Hello");
        // annoButton.setVisible(true);
        // annoButton.addActionListener(new ActionListener() {
        // @Override
        // public void actionPerformed(ActionEvent e) {
        // saveOption = CollabVizConstants.ANNOTATION;
        // }
        // });

        // JRadioButtonMenuItem notesButton = new JRadioButtonMenuItem(
        // new ImageIcon(this.getClass().getResource(
        // CollabVizConstants.SL_NOTES_IMG)));
        // notesButton.setMnemonic(KeyEvent.VK_P);
        // notesButton.setActionCommand("Hello");
        // notesButton.setVisible(true);
        // notesButton.addActionListener(new ActionListener() {
        // @Override
        // public void actionPerformed(ActionEvent e) {
        // saveOption = CollabVizConstants.NOTES;
        // }
        // });

        // ButtonGroup buttonGroup = new ButtonGroup();
        // buttonGroup.add(annoButton);
        // buttonGroup.add(notesButton);
        // radioPanel.add(annoButton);
        // radioPanel.add(notesButton);

        // notesPanel.add(radioPanel);
        // notesPanel.add(notesAreaScroll);
        // notesPanel.add(notesSaveButton);

        // notesSaveButton.setMargin(new Insets(0, 0, 0, 0));
        // notesSaveButton.setBorder(null);
        // docMiscArea.setLayout(new GridLayout(2, 0));
        JScrollPane docMiscScroll = new JScrollPane(docMiscArea);
        docMiscScroll.setVisible(true);

        // SearchBar
        searchBar = new SearchBar(this);
        notesPanel.add(searchBar);
        save.add(savePanel);
        save.setSize(width, 280);

        if (windowType == 1) {// double window view
            directory2 = new FileTree(new File(propLoader
                    .getProp(CollabVizConstants.HTML_FILES_FOLDER)), 2);

            setProperties(directory2, 220, 560);
            document2 = new PaintDoc();
            document2.addMouseListener(this);
            document2.setSize(700, 560);
            document2.setDragEnabled(true);
            document2.setEditable(false);
            JScrollPane scroll2 = new JScrollPane(document2);
            scroll2.setSize(700, 560);
            toolbar2.setSize(700, 100);

            // JSplitPane sp8= new JSplitPane(JSplitPane.VERTICAL_SPLIT );
            splitScreen(sp5, viz, notes, 0, .61);
            // splitScreen( sp5, sp8, docMiscScroll, 0, 0.8 );
            JFrame newWindow = new JFrame();
            newWindow.setSize(width - 200, height - 100);
            newWindow.add(sp5);
            newWindow.setVisible(true);

            splitScreen(sp1, toolbar, scroll, 0, 0.08);
            splitScreen(sp3, toolbar2, scroll2, 0, 0.08);
            splitScreen(sp2, directory, sp1, 1, .17);
            splitScreen(sp4, sp3, directory2, 1, .5);
            JSplitPane sp7 = new JSplitPane();
            splitScreen(sp7, sp2, sp4, 1, .35);
            splitScreen(sp6, sp7, save, 0, 0.65);
            add(sp6);

        } else if (windowType == 0) {// single window view

            // splitScreen(sp1, viz, notesScroll, 0, .61);
            splitScreen(sp1, viz, notes, 0, .61);
            // splitScreen(sp5, scroll, docMiscScroll, 0, 0.8);
            // splitScreen(sp2, sp5, sp1, 1, .55);

            // uncommenting the notes and annotation part
            splitScreen(sp5, sp1, docMiscScroll, 0, 0.8);
            splitScreen(sp6, toolbar, scroll, 0, 0.08);

            splitScreen(sp2, sp6, sp5, 1, .55);
            // splitScreen( sp2, sp6, sp1, 1, .55 );
            // splitScreen( save, saveScrollPanel,saveBarPanel, 0,.5);
            // splitScreen( save, saveBarPanel, saveScrollPanel, 0);

            // save.add(progressBar);
            splitScreen(sp4, directory, sp2, 1, 0.17);
            splitScreen(sp3, sp4, save, 0, 0.65);
            // add(sp4);
            add(sp3);
        } else if (windowType == 2) {// multiple window view
            // layout = new GroupLayout(multipleDocs);
            // multipleDocs.setLayout(layout);
            // layout.setAutoCreateGaps(false);
            // layout.setAutoCreateContainerGaps(true);
            // hGroup = layout.createSequentialGroup();
            // vGroup= layout.createSequentialGroup();
            multipleDocs.setBackground(Color.GRAY);
            multipleDocs.setSize(700, 560);
            ChangeListener changeListener = new ChangeListener() {
                public void stateChanged(ChangeEvent changeEvent) {
                    ClosableTabbedPane tabbedPane = (ClosableTabbedPane) changeEvent
                            .getSource();
                    int index = tabbedPane.getSelectedIndex();
                    if (index != -1 && openTabs.size() > 0) {
                        String absPath = openTabs.get(index);
                        saveCurrentPath(absPath);
                        getFileTree().expandTreeByPath(absPath, false);
                        System.out.println("Tab changed to: ");
                    }
                }
            };
            multipleDocs.addChangeListener(changeListener);

            // OverlayLayout overlay = new OverlayLayout(multipleDocs);
            // multipleDocs.setLayout( overlay );
            if (selectedView == ALL_VIEW) {
                splitScreen(sp1, viz, notes, 0, .61);
                splitScreen(sp2, multipleDocs, sp1, 1, .55);
            } else if (selectedView == NO_VIZ_VIEW) {
                JPanel gray = new JPanel();
                gray.setSize(360, 220);
                splitScreen(sp1, gray, notes, 0, .61);
                splitScreen(sp2, multipleDocs, sp1, 1, .55);
            } else if (selectedView == NO_NOTES_VIEW) {
                JPanel gray = new JPanel();
                splitScreen(sp1, viz, gray, 0, .71);
                splitScreen(sp2, multipleDocs, sp1, 1, .55);
            } else if (selectedView == NO_VIZNOTES_VIEW) {
                JPanel gray = new JPanel();
                gray.setSize(360, 660);
                splitScreen(sp2, multipleDocs, gray, 1, .60);
            }
            splitScreen(sp4, directory, sp2, 1, 0.17);
            splitScreen(sp3, sp4, save, 0, 0.65);
            add(sp3);

            tabDrag = new MouseListener() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void mouseExited(MouseEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void mousePressed(MouseEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    // TODO Auto-generated method stub

                }

            };

        }
        // createProgressBar("save to database...");
        setVisible(true);
        // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void setProperties(JComponent p, int w, int h) {
        Dimension d = new Dimension(w, h);
        p.setPreferredSize(d);
        p.setSize(d);
        p.setVisible(true);
    }

    public static void setFileTag(FileTag fileTag) {
        AllComponentsLegacy.fileTag = fileTag;
    }

    public static void setHistoryTag(FileHistoryTag historyTag) {
        AllComponentsLegacy.hisFileTag = historyTag;
    }

    public void splitScreen(JSplitPane sp, Component a, Component b, int x,
            double perc) {
        if (x == 0) {
            sp.setTopComponent(a);
            sp.setBottomComponent(b);
            sp.setSize(a.getWidth(), a.getHeight() + b.getHeight());
            sp.setPreferredSize(getSize());
        } else {
            sp.setLeftComponent(a);
            sp.setRightComponent(b);
            sp.setSize(a.getWidth() + b.getWidth(), a.getHeight());
            sp.setPreferredSize(getSize());
        }
        sp.setDividerLocation(perc);
        // sp.resetToPreferredSizes();
        sp.setVisible(true);
    }

    // public static JScrollPane createDocumentPanel() {
    // PaintDoc doc = new PaintDoc();
    // doc.setDragEnabled( true );
    // doc.setEditable( false );
    // doc.setSize(300, 300);
    // doc.setTransferHandler(new FileTransferHandler());
    // JScrollPane scroll = new JScrollPane(doc);
    // scroll.setSize(300, 300);
    // return scroll;
    // }

    private JTabbedPane addHistoryComponent(JTabbedPane notesPanel) {
        historyText = new JEditorPane();
        // historyText = new JLabel();
        historyText.setDragEnabled(true);
        historyText.setEditable(false);
        historyScroll = new JScrollPane();
        historyScroll.setAutoscrolls(true);
        historyRenderer = new HistoryRenderer();
        historyRenderer.setPropLoader(propLoader);
        historyRenderer.setXMLService(xmlService);
        searchBar = new SearchBar(this);
        historyRenderer = historyRenderer.addHistoryComponent(historyScroll,
                searchBar);
        notesPanel.addTab("History", historyScroll);
        return notesPanel;
    }

    private static JPanel savePanel = null;

    private void createFileSavePanel() {
        // create drop panel - the save panel
        savePanel = new JPanel();
        setProperties(savePanel, 1280, 280);

        canvas = new MotionCanvas(Color.white);
        canvas.setPreferredSize(new Dimension(1280, 280));
        canvas.setBorder(LineBorder.createGrayLineBorder());
        canvas.setTransferHandler(new FileTransferHandler());
        savePanel.add(canvas);
    }

    private static void init(String configFileName) throws CollabVizException {
        propLoader = new PropertyLoaderUtil(configFileName);
        xmlService = new XMLService(propLoader
                .getProp(CollabVizConstants.XML_MAPPING_FILE));
    }

    public static void fileTreeUpdateDoc(CaseNode node, boolean toolbarN,
            int window) throws IOException, CollabVizException {

        // centre the visualizatoin tree to the node
        fileTreeUpdateDoc(node, toolbarN, window, true);
    }

    public static void fileTreeUpdateDoc(CaseNode node, boolean toolbarN,
            int window, boolean rotateNodes) throws IOException,
            CollabVizException {

        // centre the visualizatoin tree to the node
        if (rotateNodes) {
            rotateVisualizationTree(node.toString());
        }
        updateDoc(node.getAbsolutePath(), toolbarN, window);
    }

    public static void visualizationUpdateDoc(final String path)
            throws IOException, CollabVizException {
        // XXX: FOR NOW!!
        // toolbar = true
        // windows = 1
        updateDoc(htmlFolderPath + path, true, 1);
    }

    private static void rotateVisualizationTree(String nodeName) {
        /**
         * viz = null; // do not change this line: it helps the GC to collect
         * the // old viz object faster // create new object viz =
         * VizDemoRadial.demo( VizDemoRadial.DATA_FILE, "name", 360, 440 );
         */

        // set focus on w/e file selected
        for (int i = 0; i < viz.getComponentCount(); i++) {
            if (viz.getComponent(i) instanceof VizDemoRadial) {
                VizDemoRadial visual = (VizDemoRadial) viz.getComponent(i);
                visual.externalSetFocus(nodeName);
                sp2.updateUI();
                break;
            }
        }
        // repaint
        viz.invalidate();
        viz.repaint();
    }

    public static void updateDoc(final String absolutePath, boolean toolbarN,
            int window) throws IOException, CollabVizException {

        File f = new File(absolutePath);
        htmlFilePath = absolutePath;
        xmlFileName = generateXmlFileNameWithTS(f.getAbsoluteFile().getName());
        if (windowType == 2) {// tabbed view
            System.out.println(" --------------- window 2 ------------------");
            PaintDoc doc = new PaintDoc();
            doc.addMouseListener(tabDrag);
            doc.setDragEnabled(true);
            doc.setEditable(false);
            doc.setSize(500, 500);
            // doc.setTransferHandler(new FileTransferHandler());
            JScrollPane scroll = new JScrollPane(doc);
            scroll.setSize(300, 300);
            // hGroup.addComponent( scroll );
            // vGroup.addComponent( scroll );
            // layout.setHorizontalGroup( hGroup );
            // layout.setVerticalGroup( vGroup );
            // scroll.setAlignmentX( multipleDocs.getAlignmentX()+x);
            // scroll.setAlignmentY( multipleDocs.getAlignmentY()+y);
            // x=(float) (x+0.1);
            // y=(float) (y+0.1);
            if (openTabs.contains(absolutePath)) {
                multipleDocs.setSelectedIndex(openTabs.indexOf(absolutePath));
            } else {
                String name = absolutePath.substring(absolutePath
                        .lastIndexOf('/') + 1, absolutePath.length() - 4);
                if (name.length() > 13) {
                    name = name.substring(0, 5) + "..."
                            + name.substring(name.length() - 5, name.length());
                }
                // multipleDocs.addTab(name, scroll);
                JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
                DocumentSearchBar search = new DocumentSearchBar(doc);
                search.setSize(700, 60);
                jsp.setTopComponent(search);
                jsp.setBottomComponent(scroll);
                jsp.setSize(700, 700 + scroll.getHeight());
                jsp.setDividerLocation(0.04);
                jsp.setVisible(true);
                jsp.setEnabled(false);
                multipleDocs.addTab(name, jsp);
                openTabs.add(absolutePath);
                multipleDocs.setSelectedIndex(openTabs.indexOf(absolutePath));
            }
            doc.setPage(f.toURI().toURL());
            doc.validate();
            sp3.validate();
            // for(int i=0; i< scroll.getComponentCount();i++){
            //
            // System.out.println("SCROLL COMPONENTS NUMMM"+i+"
            // "+scroll.getComponent(i).toString());
            // }
        } else if (window == 1) {// two windows
            System.out.println(" --------------- window 1 ------------------");
            URL pageUrl = f.toURI().toURL();
            document.setPage(pageUrl);
            document.repaint();
            if (toolbarN) {
                toolbar.update(absolutePath);
            }
            toolbar.repaintButton();
            if (window == 1) {
                sp1.repaint();
            } else {
                sp2.repaint();
            }
        } else {// one window
            System.out
                    .println(" --------------- window else ------------------");
            document2.setPage(f.toURI().toURL());
            document2.repaint();
            if (toolbarN) {
                toolbar2.update(absolutePath);
            }
            toolbar2.repaintButton();
            sp3.repaint();
        }

        Set<String> highlightTxtSet = loadFileTag(
                f.getAbsoluteFile().getName(), window);
        // loadHistory();
        loadHistoryTable(fileTag, highlightTxtSet);
    }

    public static void searchDoc(String term, int window) {

        Highlighter.HighlightPainter myHighlightPainter = new TextHighlighter(
                Color.lightGray);

        // highlight the text that is displayed on screen currently
        term = term.toLowerCase();
        try {
            Highlighter hilite;
            Document doc;
            if (window == 1) {
                hilite = document.getHighlighter();
                doc = document.getDocument();
            } else {
                hilite = document2.getHighlighter();
                doc = document2.getDocument();
            }
            String text = doc.getText(0, doc.getLength());
            text = text.toLowerCase();
            int pos = 0;
            int temPos = -1;
            // Search for pattern
            while ((pos = text.indexOf(term, pos)) >= 0) {
                // Create highlighter using private painter and apply around
                // pattern
                hilite.addHighlight(pos, pos + term.length(),
                        myHighlightPainter);
                temPos = pos;
                pos += term.length();
            }
            if (window == 1) {
                document.modelToView(temPos);
                document.repaint();
                sp2.repaint();
            } else {
                document2.modelToView(temPos);
                document2.repaint();
                sp2.repaint();
            }

        } catch (BadLocationException e) {
            System.out.println("WARN: error while highlighting...");
            // throw new CollabVizException(e);
        }
    }

    static GridLayout grid = new GridLayout(2, 1, 0, 0);

    private static JPanel save = new JPanel( /* grid */);

    private static JPanel saveBarPanel = new JPanel();

    private static JEditorPane saveTextPanel = new JEditorPane();

    JScrollPane saveScrollPanel = new JScrollPane(saveTextPanel);

    private static JProgressBar progressBar = null;

    public static void createProgressBar(String title) {
        progressBar = new JProgressBar(0, 10);
        progressBar.setStringPainted(true);
        Border border = BorderFactory.createTitledBorder(title);
        progressBar.setBorder(border);
        saveBarPanel.add(progressBar, BorderLayout.NORTH);
        progressBar.setVisible(false);
    }

    public static JProgressBar getProgressBar() {
        return progressBar;
    }

    public static JPanel getSaveBarPanel() {
        return saveBarPanel;
    }

    public static JEditorPane getSaveTextPanel() {
        return saveTextPanel;
    }

    private static Set<String> loadFileTag(String fileName, int window)
            throws CollabVizException {
        System.out.println("Loading the file tag.....");
        StringBuffer hisTextArea = new StringBuffer("");

        // int minLimit = 0;
        // int maxLimit = 0;
        // int spaceLimit = 0;
        StringBuffer hisText = new StringBuffer("");
        // Hashtable<Integer, JLabel> sliderTable = new Hashtable<Integer,
        // JLabel>();
        HashSet<String> highlightStr = new HashSet<String>();
        // default implementation for the file tag
        fileTag = new FileTag();

        xmlFileList = listXmlFilesForHtml(htmlFilePath);
        if (window == 1) {
            removeHighlights(document);
        } else {
            removeHighlights(document2);
        }

        // removeHisHighlights(historyText);

        // if (slider != null) {
        // docMiscArea.remove(slider);
        // }
        // if (notesPanel != null) {
        // docMiscArea.remove(notesPanel);
        // }

        if (xmlFileList != null && !xmlFileList.isEmpty()) {
            // minLimit = 0;
            // maxLimit = xmlFileList.size() - 1;
            // if (maxLimit > 0) {
            // spaceLimit = 1;
            // }

            // load the most recent file which has all the history data
            int xmlFileListSize = xmlFileList.size();

            String htmlFileName[] = new File(htmlFilePath).getName().split(
                    CollabVizConstants.DOT_REGEX);
            StringBuffer xmlDir = new StringBuffer(PropertyLoaderUtil
                    .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
            xmlDir.append(CollabVizConstants.FILE_DELIMITER);
            xmlDir.append(htmlFileName[0]);
            xmlDir.append(CollabVizConstants.FILE_DELIMITER);
            String fileDir = xmlDir.toString();
            xmlDir.append(xmlFileList.get(xmlFileListSize - 1));

            // sliderTable = AppUtil.getCalLabelTable(xmlFileList, fileDir,
            // xmlService);

            historyFileTag = (FileTag) xmlService.unmarshall(xmlDir.toString());
            fileTag = (FileTag) xmlService.unmarshall(xmlDir.toString());

            // loading history
            tempHisTag = null;
            // loadHistory();

            if (historyFileTag != null) {
                List<NoteTag> notes = historyFileTag.getNote();
                List<AnnotationTag> annotations = historyFileTag
                        .getAnnotation();
                if (notes != null && !notes.isEmpty()) {
                    // hisText.append("<html><body>");
                    // hisText.append("Notes: <br>");
                    for (NoteTag note : notes) {
                        // hisText.append("<font color='blue'>");
                        // hisText.append(note.getTimeStamp());
                        // hisText.append(":");
                        // hisText.append(note.getContent());
                        // hisText.append("</font>");
                        // hisText.append("<br>");
                        highlightStr.add(note.getContent());
                    }
                }
                if (annotations != null && !annotations.isEmpty()) {
                    // if (notes == null || notes.isEmpty()) {
                    // hisText.append("<html><body>");
                    // }
                    // hisText.append("Annotations:<br>");
                    for (AnnotationTag annot : annotations) {
                        // hisText.append("<font color='red'>");
                        // hisText.append(annot.getTimeStamp());
                        // hisText.append(" : ");
                        // hisText.append("<i>");
                        // hisText.append(annot.getKey());
                        // hisText.append("</i>");
                        // hisText.append(" : ");
                        // hisText.append(annot.getValue());
                        // hisText.append("</font>");
                        // hisText.append("<br>");
                        // Point commentIconPt = highlight(multipleDocs, annot
                        // .getKey(), Color.yellow);
                        // if (commentIconPt != null) {
                        // document.set((int) commentIconPt.getX(),
                        // (int) commentIconPt.getY(), annot.getKey());
                        // document.paintComponents(document.getGraphics());
                        // }
                        highlightStr.add(annot.getKey());
                        highlightStr.add(annot.getValue());
                    }
                    // if (hisText.length() > 0) {
                    // hisText.append("</body></html>");
                    // }
                }
            }
        }
        if (fileTag != null) {
            List<NoteTag> notes = fileTag.getNote();
            StringBuffer notesStr = new StringBuffer("");
            if (notes != null && !notes.isEmpty()) {
                hisTextArea.append("NOTES:\n");
                for (NoteTag note : notes) {
                    notesStr.append(note.getContent() + "\n");
                }
            }
            // loadNotes(notesStr.toString());
        } else {
            fileTag = new FileTag();
        }

        // displaying the history bar towards bottom of the doc panel
        if (historyText == null) {
            // historyText = new JLabel(hisText.toString());
        } else {
            // historyText.setText(hisText.toString());
        }
        // slider = new JSlider(minLimit, maxLimit, spaceLimit);
        // SliderChangeListener listener = new SliderChangeListener();
        // slider.addChangeListener(listener);
        // slider.setLabelTable(sliderTable);
        // slider.setMajorTickSpacing(10);
        // slider.setMinorTickSpacing(1);
        // slider.setPaintTicks(true);

        // if (maxLimit > 0) {
        // slider.setPaintLabels(true);
        // }
        // slider.setVisible(true);
        // slider.setEnabled(true);
        // slider.setBounds(0, 0, 500, 50);
        // slider.setName("");

        // docMiscArea.add(slider);
        // docMiscArea.add(notesPanel);
        highlightAnnotations(fileTag.getAnnotation());
        return highlightStr;
    }

    public static void highlightAnnotations(List<AnnotationTag> annoList) {
        if (annoList == null || annoList.isEmpty()) {
            // System.out
            // .println("WARN: The incoming annotation list is null or empty.");
            return;
        }
        removeHighlights(document);
        for (AnnotationTag annot : annoList) {
            try {
                highlight(multipleDocs, annot.getKey(), Color.yellow);
                // if (commentIconPt != null) {
                // document.set((int) commentIconPt.getX(),
                // (int) commentIconPt.getY(), annot.getKey());
                // document.paintComponents(document.getGraphics());
                // }
            } catch (Throwable th) {
                System.out
                        .println("ERROR: error while highlighting the annotations in document for -- "
                                + annot.getKey() + ":" + annot.getValue());
                th.printStackTrace();
            }
        }

    }

    public static List<String> listXmlFilesForHtml(String htmlFilePath)
            throws CollabVizException {
        if (htmlFilePath == null || StringUtils.isEmpty(htmlFilePath)) {
            return null;
        }
        String htmlFileName[] = new File(htmlFilePath).getName().split(
                CollabVizConstants.DOT_REGEX);
        StringBuffer htmlDir = new StringBuffer(PropertyLoaderUtil
                .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
        htmlDir.append(CollabVizConstants.FILE_DELIMITER);
        htmlDir.append(htmlFileName[0]);

        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                String tokens[] = name.split(CollabVizConstants.DOT_REGEX);
                if (tokens == null || tokens.length != 2) {
                    return false;
                }
                if ("xml".equals(tokens[1])) {
                    return true;
                }
                return false;
            }
        };

        File htmlDirName = new File(htmlDir.toString());
        String tempFileList[] = htmlDirName.list(filter);
        List<String> resultList = new ArrayList<String>();
        if (tempFileList != null && tempFileList.length > 0) {

            resultList = Arrays.asList(tempFileList);
        }

        return resultList;
    }

    private static void loadNotes(String notes) {
        System.out.println("Loading the notes : " + notes);
        if (notes == null || StringUtils.isEmpty(notes)) {
            notes = "";
        }
        notesArea.setText(notes);
    }

    private static String generateXmlFileName(String fileName)
            throws CollabVizException {
        StringBuffer result;
        if (fileName == null || StringUtils.isEmpty(fileName)) {
            throw new CollabVizException(
                    CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
        }
        result = new StringBuffer();
        String fileNametemp[] = fileName.split(CollabVizConstants.DOT_REGEX);
        if (fileNametemp != null && fileNametemp.length > 0) {
            result.append(propLoader
                    .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
            result.append(CollabVizConstants.FILE_DELIMITER);
            result.append(fileNametemp[0]);
            result.append(CollabVizConstants.DOT_CHAR);
            result.append(CollabVizConstants.XML);
            // }
        }
        return result.toString();
    }

    private static String generateXmlFileNameWithTS(String fileName)
            throws CollabVizException {
        StringBuffer result;
        if (fileName == null || StringUtils.isEmpty(fileName)) {
            throw new CollabVizException(
                    CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
        }
        result = new StringBuffer();
        long timestamp = System.currentTimeMillis();
        String fileNametemp[] = fileName.split(CollabVizConstants.DOT_REGEX);
        if (fileNametemp != null && fileNametemp.length > 0) {
            result.append(propLoader
                    .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
            result.append(CollabVizConstants.FILE_DELIMITER);
            result.append(fileNametemp[0]);
            AppUtil.createDir(result.toString());
            result.append(CollabVizConstants.FILE_DELIMITER);
            result.append(fileNametemp[0]);
            result.append("_");
            result.append(timestamp);
            result.append(CollabVizConstants.DOT_CHAR);
            result.append(CollabVizConstants.XML);
            // }
        }
        return result.toString();
    }

    private static void updateNotes(String notes, String xmlFileName)
            throws CollabVizException {
        if (notes == null || StringUtils.isEmpty(notes)) {
            throw new CollabVizException(
                    CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
        }
        // FileTag fileTag = null;
        if (fileTag == null) {
            fileTag = new FileTag();
            fileTag.setFilePath(htmlFilePath);
            fileTag.setName(xmlFileName);
        }
        List<NoteTag> notesTagList = fileTag.getNote();
        if (notesTagList == null || notesTagList.isEmpty()) {
            notesTagList = new ArrayList<NoteTag>();
        }
        NoteTag noteTag = new NoteTag();
        noteTag.setContent(notes);
        noteTag.setTimeStamp((new Date()).toString());
        notesTagList.add(noteTag);

        // update the history component
        fileTag.setNote(notesTagList);
        if (hisFileTag == null) {
            hisFileTag = new FileHistoryTag();
            hisFileTag.setDateTagList(new ArrayList<DateTag>());
        }
        ArrayList<DateTag> dtList = new ArrayList<DateTag>();
        DateTag dtTag = new DateTag();
        List<NoteTag> noteList = new ArrayList<NoteTag>();
        NoteTag note = new NoteTag();
        note.setContent(notes);
        noteList.add(note);
        dtTag.setTimeStamp(getDateString(xmlFileName
                .split(CollabVizConstants.DOT_REGEX)[0].split("_")[1]));
        dtTag.setFileName(new File(htmlFilePath).getName());
        dtTag.setFilePath(xmlFileName);
        dtTag.setNote(noteList);
        dtList.add(dtTag);

        hisFileTag.getDateTagList().addAll(dtList);
    }

    private void updateAnnotation(int xVal, int yVal, String key, String value,
            String xmlFileName) throws CollabVizException {
        System.out.println("updateAnnotation(): starts");

        if (key == null || StringUtils.isEmpty(key) || xmlFileName == null
                || StringUtils.isEmpty(xmlFileName)) {
            throw new CollabVizException(
                    CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
        }
        // FileTag fileTag = null;
        if (fileTag == null) {
            fileTag = new FileTag();
            fileTag.setFilePath(htmlFilePath);
            fileTag.setName(xmlFileName);
        }

        List<AnnotationTag> annoTagList = fileTag.getAnnotation();
        if (annoTagList == null || annoTagList.isEmpty()) {
            annoTagList = new ArrayList<AnnotationTag>();
        }

        // update the existing stuff
        List<AnnotationTag> modifiedList = new ArrayList<AnnotationTag>();
        boolean modified = false;
        for (AnnotationTag annotTag : annoTagList) {
            if (annotTag.getKey().equals(key)) {
                annotTag.setValue(value);
                modified = true;
            }
            modifiedList.add(annotTag);
        }
        if (modified) {
            fileTag.setAnnotation(modifiedList);
        } else {

            AnnotationTag annoTag = new AnnotationTag();
            annoTag.setKey(key);
            annoTag.setValue(value);
            annoTag.setTimeStamp((new Date()).toString());
            annoTag.setX(xVal);
            annoTag.setY(yVal);
            annoTagList.add(annoTag);
            fileTag.setAnnotation(annoTagList);
        }

        // update the history component
        if (hisFileTag == null) {
            hisFileTag = new FileHistoryTag();
            hisFileTag.setDateTagList(new ArrayList<DateTag>());
        }
        ArrayList<DateTag> dtList = new ArrayList<DateTag>();
        DateTag dtTag = new DateTag();
        List<AnnotationTag> annotList = new ArrayList<AnnotationTag>();
        AnnotationTag annot = new AnnotationTag();
        annot.setKey(key);
        annot.setValue(value);
        annotList.add(annot);
        dtTag.setFileName(new File(htmlFilePath).getName());
        dtTag.setFilePath(xmlFileName);
        dtTag.setTimeStamp(getDateString(xmlFileName
                .split(CollabVizConstants.DOT_REGEX)[0].split("_")[1]));
        dtTag.setAnnotation(annotList);
        dtList.add(dtTag);
        hisFileTag.getDateTagList().addAll(dtList);
        System.out.println("updateAnnotation(): ends");
    }

    private void removeAnnotation(String key) {
        if (key == null || StringUtils.isEmpty(key)) {
            return;
        }
        List<AnnotationTag> modifiedList = new ArrayList<AnnotationTag>();
        List<AnnotationTag> annotList = fileTag.getAnnotation();
        if (annotList != null && !annotList.isEmpty()) {
            for (AnnotationTag annot : annotList) {
                if (key.equals(annot.getKey())) {
                    continue;
                }
                modifiedList.add(annot);
            }
        }
        fileTag.setAnnotation(modifiedList);
    }

    private static Point highlight(JTextComponent textComp, String pattern,
            Color color) throws CollabVizException {

        Highlighter.HighlightPainter myHighlightPainter = new TextHighlighter(
                color);
        // List<Point> result = new ArrayList<Point>();
        Point result = new Point();

        // highlight the text that is displayed on screen currently
        pattern = pattern.toLowerCase();
        try {
            Highlighter hilite = textComp.getHighlighter();
            Document doc = textComp.getDocument();
            String text = doc.getText(0, doc.getLength());
            text = text.toLowerCase();
            int pos = 0;
            int temPos = -1;
            // Search for pattern
            while ((pos = text.indexOf(pattern, pos)) >= 0) {
                // Create highlighter using private painter and apply around
                // pattern
                hilite.addHighlight(pos, pos + pattern.length(),
                        myHighlightPainter);
                temPos = pos;
                pos += pattern.length();
            }
            Rectangle rect = document.modelToView(temPos);
            result.x = (int) rect.getMaxX();
            result.y = (int) rect.getMinY() - 30;

        } catch (BadLocationException e) {
            System.out.println("WARN: error while highlighting...");
            // throw new CollabVizException(e);
        }
        return result;
    }

    private static Point highlight(ClosableTabbedPane tabbedPane,
            String pattern, Color color) throws CollabVizException {
        JSplitPane splitPane = (JSplitPane) tabbedPane.getSelectedComponent();
        // if (splitPane.getLeftComponent() instanceof JTextComponent) {
        // System.out.println("-----------");
        // } else if (splitPane.getRightComponent() instanceof JTextComponent) {
        // System.out.println("------ right -----");
        // }
        JScrollPane textScroll = (JScrollPane) splitPane.getRightComponent();
        JTextComponent textComp = (JTextComponent) textScroll.getViewport()
                .getView();

        Highlighter.HighlightPainter myHighlightPainter = new TextHighlighter(
                color);
        // List<Point> result = new ArrayList<Point>();
        Point result = new Point();

        // highlight the text that is displayed on screen currently
        pattern = pattern.toLowerCase();
        try {

            Highlighter hilite = textComp.getHighlighter();
            Document doc = textComp.getDocument();
            String text = doc.getText(0, doc.getLength());
            text = text.toLowerCase();
            int pos = 0;
            int temPos = -1;
            // Search for pattern
            while ((pos = text.indexOf(pattern, pos)) >= 0) {
                // Create highlighter using private painter and apply around
                // pattern

                hilite.addHighlight(pos, pos + pattern.length(),
                        myHighlightPainter);
                temPos = pos;
                pos += pattern.length();
            }
            // Rectangle rect = document.modelToView(temPos);
            // result.x = (int) rect.getMaxX();
            // result.y = (int) rect.getMinY() - 30;

        } catch (BadLocationException e) {
            System.out.println("WARN: error while highlighting...");
            throw new CollabVizException(e);
        }
        return result;
    }

    // COMENTING AS THE CODE IS NOT USED
    // private static class SliderChangeListener implements ChangeListener {

    // public void stateChanged(ChangeEvent e) {
    // JSlider source = (JSlider) e.getSource();
    // if (!source.getValueIsAdjusting()) {
    // int fps = (int) source.getValue();
    // try {
    // loadFiles(fps);
    // } catch (CollabVizException exp) {
    // exp.printStackTrace();
    // }
    // }
    // }
    // }
    // private static void loadFiles(int fileNumber) throws CollabVizException {
    // if (fileNumber < 0) {
    // return;
    // }
    // removeHighlights(document);
    // int fileIndex = 0;
    // if (fileNumber > 0) {
    // fileIndex = fileNumber - 1;
    // }
    // System.out.println("File index: " + fileIndex + " fileNumber: "
    // + fileNumber);
    // String xmlFileName = xmlFileList.get((fileNumber)).split(
    // CollabVizConstants.DOT_REGEX)[0];
    // System.out.println("File selected : " + xmlFileName);
    // StringBuffer tempHtmlPath = new StringBuffer("");
    // tempHtmlPath.append(PropertyLoaderUtil
    // .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
    // tempHtmlPath.append(CollabVizConstants.FILE_DELIMITER);
    // tempHtmlPath.append(new File(htmlFilePath).getAbsoluteFile().getName()
    // .split(CollabVizConstants.DOT_REGEX)[0]);
    // tempHtmlPath.append(CollabVizConstants.FILE_DELIMITER);
    // tempHtmlPath.append(xmlFileName);
    // tempHtmlPath.append(CollabVizConstants.DOT_CHAR);
    // tempHtmlPath.append("xml");
    // System.out.println("INFO: File loaded: " + tempHtmlPath.toString());
    // load the file xml
    // fileTag = (FileTag) xmlService.unmarshall(tempHtmlPath.toString());
    // List<AnnotationTag> annoTagList = fileTag.getAnnotation();
    // if (annoTagList != null && !annoTagList.isEmpty()) {
    // StringBuffer annoText = new StringBuffer("");
    // int xVal = 0;
    // int yVal = 0;
    // for (AnnotationTag anno : annoTagList) {
    // annoText.append(anno.getKey());
    // xVal = anno.getX();
    // yVal = anno.getY();
    // highlight(document, anno.getKey(), Color.YELLOW);
    // document.set(xVal, yVal, anno.getKey());
    // document.paintComponents(document.getGraphics());
    // }
    // }
    // StringBuffer notes = new StringBuffer("");
    // List<NoteTag> notesList = fileTag.getNote();
    // if (notesList != null && !notesList.isEmpty()) {
    // for (NoteTag noteTag : notesList) {
    // notes.append(noteTag.getContent());
    // notes.append("\n");
    // }
    // }
    // System.out.println("Notes: " + notes.toString());
    // loadNotes(notes.toString());
    // }
    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    // COMMENTED AS THIS CODE IS NOT USED ANY MORE
    // private static void removeCommentsComponents(String selectedText,
    // List<AnnotationTag> annotList) {
    // if (annotList == null || annotList.isEmpty()) {
    // Component compList[] = document.getComponents();
    // if (compList != null && compList.length > 0) {
    // for (Component component : compList) {
    // if (component instanceof JLabel) {
    // JLabel label = (JLabel) component;
    // if (selectedText.equals(label.getName())) {
    // label.setEnabled(false);
    // label.setVisible(false);
    // document.remove(label);
    // }
    // }
    // }
    // }
    // } else {
    // for (AnnotationTag annotTag : annotList) {
    // Component compList[] = document.getComponents();
    // if (compList != null && compList.length > 0) {
    // for (Component component : compList) {
    // if (component instanceof JLabel) {
    // JLabel label = (JLabel) component;
    // if (annotTag.getKey().equals(label.getName())) {
    // label.setEnabled(false);
    // label.setVisible(false);
    // document.remove(label);
    // }
    // }
    // }
    // }
    // }
    // }
    // }

    public static void removeHighlights(JTextComponent textComp) {
        Highlighter hilite = textComp.getHighlighter();
        if (hilite == null) {
            return;
        }
        Highlighter.Highlight[] hilites = hilite.getHighlights();

        if (hilites == null || hilites.length == 0) {
            return;
        }
        for (int i = 0; i < hilites.length; i++) {

            hilite.removeHighlight(hilites[i]);
        }
        // added here for temp fix
        Component compoList[] = document.getComponents();
        if (compoList != null && compoList.length > 0) {
            for (Component compo : compoList) {
                if (compo instanceof JLabel) {
                    compo.setVisible(false);
                    compo.setEnabled(false);
                    document.remove(compo);
                }
            }
        }
    }

    // COMMENTED AS THIS METHOD IS NOT USED ANY MORE
    // private static void removeHisHighlights(JTextComponent textComp) {
    // Highlighter hilite = textComp.getHighlighter();
    // if (hilite == null) {
    // return;
    // }
    // Highlighter.Highlight[] hilites = hilite.getHighlights();
    // if (hilites == null || hilites.length == 0) {
    // return;
    // }
    // for (int i = 0; i < hilites.length; i++) {
    // hilite.removeHighlight(hilites[i]);
    // }
    // }

    // COMMENTED AS THIS METHOD IS NOT USED ANY MORE
    // private class NotesActionListener implements ActionListener {
    // @Override
    // public void actionPerformed(ActionEvent e) {
    // String notes = notesArea.getText();
    // LOGGER.log(Location.NH,
    // "user clicked the Save button for notes/annotation");
    // if (saveOption == null || StringUtils.isEmpty(saveOption)) {
    // JOptionPane.showMessageDialog(null,
    // "Please select either the notes or annotation icon.",
    // "Error", JOptionPane.ERROR_MESSAGE);
    // LOGGER
    // .log(Location.NH,
    // "Error message: user didnt select either notes or annotation icon");
    // return;
    // }
    // if (notes == null || StringUtils.isEmpty(notes)) {
    // System.out
    // .println("NotesActionListener(): actionPerformed(): There are no notes to
    // be marked.");
    // JOptionPane.showMessageDialog(null,
    // "Please enter notes in the text area.", "Error",
    // JOptionPane.ERROR_MESSAGE);
    // LOGGER
    // .log(Location.NH,
    // "Error message:user didnt enter the notes in text area");
    // return;
    // }
    // if (saveOption.equals(CollabVizConstants.ANNOTATION)) {
    // String tokens[] = notes.split(":");
    // if (tokens == null || tokens.length != 2) {
    // JOptionPane
    // .showMessageDialog(
    // null,
    // "Please enter annotation in format <key_text>:<value_text>",
    // "Error", JOptionPane.ERROR_MESSAGE);
    // LOGGER
    // .log(Location.NH,
    // "Error message:user didnt enter the annotation in the format.");
    // return;
    // }
    // try {
    // Point point = highlight(document, tokens[0], Color.yellow);
    // if (point != null) {
    // updateAnnotation((int) point.getX(),
    // (int) point.getY(), tokens[0], tokens[1],
    // xmlFileName);
    // xmlService.marshall(xmlFileName, fileTag);
    // xmlService.marshall(historyFilePath, hisFileTag);
    // JOptionPane.showMessageDialog(null,
    // "The annotation is saved successfully.",
    // "Message", JOptionPane.PLAIN_MESSAGE);
    // LOGGER.log(Location.NH, "Annotation saved.");
    // // highlighting part
    // document.set((int) point.getX(), (int) point.getY(),
    // tokens[0]);
    // document.paintComponents(document.getGraphics());
    // } else {
    // JOptionPane.showMessageDialog(null,
    // "Error while saving the annotation.", "Error",
    // JOptionPane.ERROR_MESSAGE);
    // LOGGER
    // .log(Location.NH,
    // "Error message: error while saving the annotation");
    // }
    // } catch (CollabVizException exp) {
    // exp.printStackTrace();
    // JOptionPane.showMessageDialog(null,
    // "Error while saving the annotation.", "Error",
    // JOptionPane.ERROR_MESSAGE);
    // LOGGER.log(Location.NH,
    // "Error message: error while saving the annotation");
    // }
    // }

    // if (saveOption.equals(CollabVizConstants.NOTES)) {
    // try {
    // updateNotes(notes, xmlFileName);
    // xmlService.marshall(xmlFileName, fileTag);
    // xmlService.marshall(historyFilePath, hisFileTag);
    // JOptionPane.showMessageDialog(null,
    // "The notes is saved successfully.", "Message",
    // JOptionPane.PLAIN_MESSAGE);
    // LOGGER.log(Location.NH, "Note saved.");
    // } catch (CollabVizException ex) {
    // ex.printStackTrace();
    // JOptionPane.showMessageDialog(null,
    // "Error while saving the notes.", "Error",
    // JOptionPane.ERROR_MESSAGE);
    // }
    // }
    // }
    // }

    // private static void loadHistory() throws CollabVizException {
    // if (htmlFilePath == null || StringUtils.isEmpty(htmlFilePath)) {
    // System.out.println("ERROR: No Html file is loaded...");
    // return;
    // }
    // if (historyFilePath == null || StringUtils.isEmpty(historyFilePath)) {
    // StringBuffer historyFile = new StringBuffer(propLoader
    // .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
    // historyFile.append(CollabVizConstants.FILE_DELIMITER);
    // historyFile.append(CollabVizConstants.HISTORY_FILE_NAME);
    // historyFilePath = historyFile.toString();
    // }

    // if (tempHisTag == null) {
    // hisFileTag = (FileHistoryTag) xmlService
    // .unmarshall(historyFilePath);
    // } else {
    // if (hisFileTag == null) {
    // hisFileTag = new FileHistoryTag();
    // hisFileTag.setDateTagList(tempHisTag.getDateTagList());
    // } else {
    // List<DateTag> dtTagList = hisFileTag.getDateTagList();
    // dtTagList.addAll(tempHisTag.getDateTagList());
    // hisFileTag.setDateTagList(dtTagList);
    // xmlService.marshall(historyFilePath, hisFileTag);
    // }
    // }

    // if (hisFileTag == null) {
    // System.out.println("WARN: No history to be loaded.");
    // return;
    // }
    // StringBuffer history = new StringBuffer("");
    // List<DateTag> dateTagList = hisFileTag.getDateTagList();
    // if (dateTagList != null && !dateTagList.isEmpty()) {
    // history
    // .append("<html><body bgcolor='#FAF8CC'><font size=3 face='Arial'>");
    // // Change teh color of the background in the
    // for (DateTag dateTg : dateTagList) {
    // // for (int count = (dateTagList.size() - 1); count >= 0;
    // // count--) {
    // // DateTag dateTg = dateTagList.get(count);
    // List<AnnotationTag> annotTagList = dateTg.getAnnotation();
    // if (annotTagList != null && !annotTagList.isEmpty()) {
    // for (AnnotationTag annotTag : annotTagList) {
    // history.append("<font color='red'>");
    // history.append("<i>");
    // history.append(annotTag.getKey());
    // history.append("</i>");
    // history.append(" : ");
    // history.append(annotTag.getValue());
    // history.append("</font>");
    // history.append(" : ");
    // history.append(dateTg.getFileName());
    // history.append(" : ");
    // history.append(dateTg.getTimeStamp());
    // history.append("<br>");
    // }
    // }
    // history.append("<br>");
    // List<NoteTag> noteList = dateTg.getNote();
    // if (noteList != null && !noteList.isEmpty()) {
    // for (NoteTag note : noteList) {
    // history.append("<font color='blue'>");
    // history.append(note.getContent());
    // history.append("</font>");
    // history.append(" : ");
    // history.append(dateTg.getFileName());
    // history.append(" : ");
    // history.append(dateTg.getTimeStamp());
    // history.append("<br>");
    // }
    // }
    // }
    // history.append("</font></body></html>");
    // }
    // if (historyText == null) {
    // historyText = new JEditorPane();
    // }
    // try {
    // File htmlFile = new File(htmlFilePath);
    // File tempFile = new File(PropertyLoaderUtil
    // .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH)
    // + CollabVizConstants.FILE_DELIMITER + "temp.html");
    // FileUtils.writeStringToFile(tempFile, history.toString());
    // historyText.setPage(htmlFile.toURI().toURL());
    // historyText.setPage(tempFile.toURI().toURL());
    // historyText.repaint();
    // sp1.repaint();
    // history text higlighting
    // if (fileTag != null) {
    // List<AnnotationTag> annoList = fileTag.getAnnotation();
    // if (annoList != null && !annoList.isEmpty()) {
    // for (AnnotationTag annot : annoList) {
    // highlight(historyText, annot.getKey(), Color.yellow);
    // highlight(historyText, annot.getValue(), Color.yellow);
    // }
    // }
    // List<NoteTag> notesList = fileTag.getNote();
    // if (notesList != null && !notesList.isEmpty()) {
    // for (NoteTag note : notesList) {
    // highlight(historyText, note.getContent(), Color.yellow);
    // }
    // }
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // System.out
    // .println("ERROR: error while loading the history component");
    // }
    // }

    private static String getDateString(String timeStamp) {
        if (timeStamp == null || StringUtils.isEmpty(timeStamp)) {
            return (new Date().toString());
        }
        DateFormat formatter = new SimpleDateFormat(
                CollabVizConstants.DATE_FORMAT);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(Long.parseLong(timeStamp));
        return (formatter.format(cal.getTime()));
    }

    // COMMENTED AS THIS METHOD IS NOT USED ANY MORE
    // private static void highlightAnnotation(String annotText) {
    // if (annotText == null || StringUtils.isEmpty(annotText)) {
    // return;
    // }
    // removeHisHighlights(historyText);
    // try {
    // highlight(historyText, annotText, Color.yellow);

    // Highlighter hilite = historyText.getHighlighter();
    // if (hilite == null) {
    // return;
    // }
    // Highlighter.Highlight[] hilites = hilite.getHighlights();
    // if (hilites != null && hilites.length > 0) {
    // for (Highlighter.Highlight hili : hilites) {
    // try {

    // Rectangle rect = historyText.modelToView(hili
    // .getStartOffset());
    // historyText.scrollRectToVisible(rect);
    // LOGGER.log(Location.NH,
    // "History window: Scroll bar moved.");
    // break;
    // } catch (BadLocationException exp) {
    // System.out
    // .println("ERROR: error in scrolling the bar to the highlighted
    // annotation.");
    // }
    // }

    // }

    // } catch (CollabVizException e) {
    // System.out
    // .println("ERROR: error while highlighting the annotation.");
    // e.printStackTrace();
    // }
    // }

    public static void highlightAnnotInHistoryTable(String key, String value) {
        if (key == null || StringUtils.isEmpty(key) || value == null
                || StringUtils.isEmpty(value)) {
            return;
        }
        HashSet<String> cellValueSet = new HashSet<String>();
        cellValueSet.add(key);
        cellValueSet.add(value);
        Rectangle rect = historyRenderer.highlightTextSet(cellValueSet);
        if (rect != null) {
            historyRenderer.getJeksTable().scrollRectToVisible(rect);
        }
    }

    private static void loadHistoryTable(FileTag fileTag, Set<String> highText)
            throws CollabVizException {
        if (htmlFilePath == null || StringUtils.isEmpty(htmlFilePath)) {
            System.out.println("ERROR: No Html file is loaded...");
            return;
        }
        if (historyFilePath == null || StringUtils.isEmpty(historyFilePath)) {
            StringBuffer historyFile = new StringBuffer(propLoader
                    .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
            historyFile.append(CollabVizConstants.FILE_DELIMITER);
            historyFile.append(CollabVizConstants.HISTORY_FILE_NAME);
            historyFilePath = historyFile.toString();
        }

        // if (tempHisTag == null) {
        hisFileTag = (FileHistoryTag) xmlService.unmarshall(historyFilePath);
        // } else {
        if (hisFileTag == null) {
            hisFileTag = new FileHistoryTag();
            // hisFileTag.setDateTagList(tempHisTag.getDateTagList());
            System.out.println("WARN: No history to be loaded.");
        }
        // else {
        // List<DateTag> dtTagList = hisFileTag.getDateTagList();
        // dtTagList.addAll(tempHisTag.getDateTagList());
        // hisFileTag.setDateTagList(dtTagList);
        // xmlService.marshall(historyFilePath, hisFileTag);
        // }
        // }

        historyRenderer.setFileTag(fileTag);
        historyRenderer.setXMLFileName(xmlFileName);
        historyRenderer.setHtmlFilePath(htmlFilePath);
        historyRenderer.setHistoryTag(hisFileTag);
        Rectangle rect = historyRenderer.loadDataOri(highText);
        historyRenderer.setViewportViewForHistory(historyScroll);
        JScrollBar scrollBar = historyScroll.getVerticalScrollBar();
        scrollBar.setValue(scrollBar.getMaximum());

        // for the search within history content
        historyRenderer.loadData(highText, null);
        // historyScroll.setViewportView(historyRenderer.getJeksTable());
        // if (rect != null) {
        // historyRenderer.getJeksTable().scrollRectToVisible(rect);
        // historyRenderer.scrollToBotton(rect);

        // }
    }

    public static HistoryRenderer getHistoryRenderer() {
        return historyRenderer;
    }

    public static FileTree getFileTree() {
        return (FileTree) directory;
    }

    public static JEditorPane getDocumentPane() {
        return (JEditorPane) document;
    }

    public static ClosableTabbedPane getMultipleDocs() {
        return multipleDocs;
    }

    private static String previousAbsPath = null;
    private static String currentAbsPath = null;

    public static String getPreviousPath() {
        return previousAbsPath;
    }

    public static void saveCurrentPath(String absPath) {
        previousAbsPath = currentAbsPath;
        currentAbsPath = absPath;
    }

    public static String getCurrentPath() {
        return currentAbsPath;
    }
}
